<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="姓名" prop="realName">
        <el-input v-model="queryParams.realName" placeholder="请输入姓名" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="身份证" prop="idCard">
        <el-input v-model="queryParams.idCard" placeholder="请输入身份证" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="职级" prop="postRank">
        <el-select v-model="queryParams.postRank" placeholder="请选择职级" clearable>
          <el-option v-for="dict in dict.type.customer_post_rank" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="客户" prop="customerName">
        <el-input v-model="queryParams.customerName" placeholder="请输入客户" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['system:customer:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['system:customer:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:customer:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['system:customer:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="customerList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="用户ID" align="center" prop="id" />
      <el-table-column label="姓名" align="center" prop="realName" />
      <el-table-column label="身份证" align="center" prop="idCard" />
      <el-table-column label="岗位" align="center" prop="postName" />
      <el-table-column label="职级" align="center" prop="postRank">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.customer_post_rank" :value="scope.row.postRank" />
        </template>
      </el-table-column>
      <el-table-column label="项目类型" align="center" prop="projectType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.contract_type" :value="scope.row.projectType" />
        </template>
      </el-table-column>
      <el-table-column label="地域" align="center" prop="areaName" />
      <el-table-column label="业务线" align="center" prop="businessLineName" />
      <el-table-column label="事业部" align="center" prop="businessDepartmentName" />
      <el-table-column label="交付部" align="center" prop="deliveryDepartmentName" />
      <el-table-column label="客户" align="center" prop="customerName" />
      <el-table-column label="GP1%目标值" align="center" prop="gp1TargetValue" />
      <el-table-column label="转正薪酬" align="center" prop="regularSalary" />
      <el-table-column label="公司缴纳五险一金" align="center" prop="fiveInsuranceAndOnePension" />
      <el-table-column label="实际GP1%" align="center" prop="gp1RealityValue" />
      <el-table-column label="与目标值偏差" align="center" prop="deviationFromTargetValue" />
      <el-table-column label="奖金系数" align="center" prop="bonusFactor" />
      <el-table-column label="是否有上家公司流水" align="center" prop="havaLastCompanyBill" />
      <el-table-column label="上家公司月薪" align="center" prop="lastCompanyMonthlySalary" />
      <el-table-column label="员工状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.customer_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="入职日期" align="center" prop="entryDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.entryDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:customer:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:customer:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改客户信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="60%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="姓名" prop="realName">
              <el-input v-model="form.realName" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身份证" prop="idCard">
              <el-input v-model="form.idCard" placeholder="请输入身份证" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="合同" prop="contractId">
              <el-select @change="handleTypeChange" v-model="form.contractId" placeholder="请选择合同" style="width: 100%;">
                <el-option v-for="dict in contractOptions" :key="dict.id" :label="dict.name"
                  :value="parseInt(dict.id)"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户" prop="customerName">
              <el-input disabled v-model="form.customerName" placeholder="自动填入" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="岗位" prop="postId">
              <el-select v-model="form.postId" placeholder="请选择岗位" style="width: 100%;">
                <el-option v-for="dict in postOptions" :key="dict.postId" :label="dict.postName"
                  :value="parseInt(dict.postId)"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职级" prop="postRank">
              <el-select v-model="form.postRank" placeholder="请选择职级" style="width: 100%;">
                <el-option v-for="dict in dict.type.customer_post_rank" :key="dict.value" :label="dict.label"
                  :value="parseInt(dict.value)"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row> <el-row>
          <el-col :span="12">
            <el-form-item label="项目类型" prop="projectType">
              <el-select disabled v-model="form.projectType" placeholder="自动填入" style="width: 100%;">
                <el-option v-for="dict in dict.type.contract_type" :key="dict.value" :label="dict.label"
                  :value="parseInt(dict.value)" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="地域" prop="areaId">
              <el-select v-model="form.areaId" placeholder="请选择地域" style="width: 100%;">
                <el-option v-for="dict in areaOptions" :key="dict.id" :label="dict.name"
                  :value="parseInt(dict.id)"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="业务线" prop="businessLineId">
              <el-select v-model="form.businessLineId" placeholder="请选择业务线" style="width: 100%;">
                <el-option v-for="dict in businesslineOptions" :key="dict.id" :label="dict.name"
                  :value="parseInt(dict.id)"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="事业部">
              <el-input disabled v-model="form.businessDepartmentName" placeholder="自动填入" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="交付部">
              <el-input disabled v-model="form.deliveryDepartmentName" placeholder="自动填入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="GP1%目标值" prop="gp1TargetValue">
              <el-input disabled v-model="form.gp1TargetValue" placeholder="自动填入" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="转正薪酬（元）" prop="regularSalary">
              <el-input-number v-model="form.regularSalary" placeholder="请输入转正薪酬" :controls="false" :precision="2"
                style="width: 100%;" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公司缴纳五险一金（元）" prop="fiveInsuranceAndOnePension">
              <el-input-number v-model="form.fiveInsuranceAndOnePension" :controls="false" :precision="2"
                style="width:100%" placeholder="请输入公司缴纳五险一金" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">

            <el-form-item label="实际GP1%" prop="gp1RealityValue">
              <el-input disabled v-model="form.gp1RealityValue" placeholder="自动填入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="与目标值偏差" prop="deviationFromTargetValue">
              <el-input disabled v-model="form.deviationFromTargetValue" placeholder="自动填入" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <!-- <el-col :span="12">
            <el-form-item label="奖金系数">
              <el-input disabled v-model="form.bonusFactor" placeholder="自动填入" />
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="员工状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择员工状态" style="width: 100%;">
                <el-option v-for="dict in dict.type.customer_status" :key="dict.value" :label="dict.label"
                  :value="parseInt(dict.value)"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否有上家公司流水（元）" prop="havaLastCompanyBill">
              <el-radio-group v-model="form.havaLastCompanyBill" class="ml-4">
                <el-radio :label="1" size="large">是</el-radio>
                <el-radio :label="2" size="large">否</el-radio>
              </el-radio-group>
              <el-input-number v-model="form.lastCompanyMonthlySalary" :controls="false" :precision="2" style="width:100%"
                placeholder="请输入上家公司月薪" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="入职日期" prop="entryDate">
              <el-date-picker clearable v-model="form.entryDate" type="date" style="width: 100%;"
                value-format="yyyy-MM-dd" placeholder="请选择入职日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCustomer, getCustomer, delCustomer, addCustomer, updateCustomer, listContractApi, listBusinesslineApi, getDetailApi } from "@/api/system/customer";
import { listBussinessdeptApi, listDeliverydeptApi, listAreaApi, listPostApi } from "@/api/system/contract";

export default {
  name: "Customer",
  dicts: ['customer_post_rank', 'customer_status', 'contract_type'],
  data () {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 客户信息表格数据
      customerList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        realName: null,
        idCard: null,
        postRank: null,
        projectType: null,
        areaId: null,
        businessLineId: null,
        businessDepartmentId: null,
        deliveryDepartmentId: null,
        customerName: null,
        havaLastCompanyBill: null,
        status: null,
        contractId: null
      },
      // 表单参数
      form: {
        contractId: null,
        areaId: null, postId: null, postRank: null, regularSalary: null, fiveInsuranceAndOnePension: null
      },
      // 表单校验
      rules: {
        realName: [
          { required: true, message: "姓名不能为空", trigger: "blur" }
        ],
        idCard: [
          { required: true, message: "身份证不能为空", trigger: "blur" }
        ],
        postId: [
          { required: true, message: "岗位id不能为空", trigger: "blur" }
        ],
        postName: [
          { required: true, message: "岗位不能为空", trigger: "blur" }
        ],
        postRank: [
          { required: true, message: "职级不能为空", trigger: "change" }
        ],
        projectType: [
          { required: true, message: "项目类型不能为空", trigger: "change" }
        ],
        areaId: [
          { required: true, message: "地域id不能为空", trigger: "blur" }
        ],
        areaName: [
          { required: true, message: "地域不能为空", trigger: "blur" }
        ],
        businessLineId: [
          { required: true, message: "业务线id不能为空", trigger: "blur" }
        ],
        businessLineName: [
          { required: true, message: "业务线不能为空", trigger: "blur" }
        ],
        businessDepartmentId: [
          { required: true, message: "事业部id不能为空", trigger: "blur" }
        ],
        deliveryDepartmentId: [
          { required: true, message: "交付部id不能为空", trigger: "blur" }
        ],
        customerName: [
          { required: true, message: "客户不能为空", trigger: "blur" }
        ],
        contractName: [
          { required: true, message: "合同名称不能为空", trigger: "blur" }
        ],
        gp1TargetValue: [
          { required: true, message: "GP1%目标值不能为空", trigger: "blur" }
        ],
        regularSalary: [
          { required: true, message: "转正薪酬不能为空", trigger: "blur" }
        ],
        fiveInsuranceAndOnePension: [
          { required: true, message: "公司缴纳五险一金不能为空", trigger: "blur" }
        ],
        gp1RealityValue: [
          { required: true, message: "实际GP1%不能为空", trigger: "blur" }
        ],
        deviationFromTargetValue: [
          { required: true, message: "与目标值偏差不能为空", trigger: "blur" }
        ],
        bonusFactor: [
          { required: true, message: "奖金系数不能为空", trigger: "blur" }
        ],
        havaLastCompanyBill: [
          { required: true, message: "是否有上家公司流水不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "员工状态不能为空", trigger: "change" }
        ],
        entryDate: [
          { required: true, message: "入职日期不能为空", trigger: "blur" }
        ],
        contractId: [
          { required: true, message: "合同id不能为空", trigger: "blur" }
        ]
      },
      contractOptions: [],
      postOptions: [],
      areaOptions: [],
      businesslineOptions: [], // 业务线
      settPrice: null,
      isWatch: true
    };
  },
  created () {
    this.initOptions()
    this.getList();
  },
  computed: {
    formChange () {
      const { contractId, areaId, postId, postRank } = this.form
      return { contractId, areaId, postId, postRank }
    },
    priceChange () {
      const { regularSalary, fiveInsuranceAndOnePension } = this.form
      return { regularSalary, fiveInsuranceAndOnePension }
    },
    isComputed () {
      return this.isNot(this.form.contractId) && this.isNot(this.form.areaId) && this.isNot(this.form.postId) && this.isNot(this.form.postRank)
    }
  },
  watch: {
    formChange () {
      if (this.isComputed) {
        this.getData()
      }
    },
    priceChange () {
      this.isWatch && this.setPrice()
    }
  },
  methods: {
    // 计算实际GP1
    setPrice () {
      console.log(this.settPrice)
      if (!this.isNot(this.settPrice)) return
      const { regularSalary, fiveInsuranceAndOnePension, gp1TargetValue } = this.form
      const totalPrice = +regularSalary + +fiveInsuranceAndOnePension
      const gp1RealityValue = totalPrice / this.settPrice
      // 实际
      this.form.gp1RealityValue = Math.floor(gp1RealityValue * 100) / 100
      // 偏差
      this.form.deviationFromTargetValue = Math.floor((gp1RealityValue - gp1TargetValue) * 100) / 100
      console.log(totalPrice);
    },
    // 获取目标GP1
    getData () {
      getDetailApi(this.formChange).then(res => {
        this.form.gp1TargetValue = res.data.gp1TargetValue
        this.settPrice = res.data.settPrice
        this.setPrice()
        // this.form.gp1RealityValue = res.data.gp1RealityValue
        // this.form.deviationFromTargetValue = res.data.deviationFromTargetValue
        // this.form.bonusFactor = res.data.bonusFactor
      })
    },
    isNot (val) {
      return (val ?? '' !== '')
    },
    /** 查询配置项 */
    initOptions () {
      listContractApi().then(res => {
        this.contractOptions = res.data
      })
      listDeliverydeptApi().then(res => {
        this.deliverydeptOptions = res.data
      })
      listAreaApi().then(res => {
        this.areaOptions = res.data
      })
      listPostApi().then(res => {
        this.postOptions = res.data
      })
      listBusinesslineApi().then(res => {
        this.businesslineOptions = res.data
      })

    },
    /** 选择合同 */
    handleTypeChange (e) {
      const contract = this.contractOptions.find(item => item.id == e)
      this.form.customerName = contract.customerName // 客户
      this.form.deliveryDepartmentName = contract.deliverName // 交付
      this.form.deliveryDepartmentId = contract.deliverId // 交付
      this.form.businessDepartmentName = contract.businessName // 事业
      this.form.businessDepartmentId = contract.businessId // 事业
      this.form.projectType = contract.type // 项目类型

    },
    /** 查询客户信息列表 */
    getList () {
      this.loading = true;
      listCustomer(this.queryParams).then(response => {
        this.customerList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel () {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset () {
      this.form = {
        id: null,
        realName: null,
        idCard: null,
        postId: null,
        postName: null,
        postRank: null,
        projectType: null,
        areaId: null,
        areaName: null,
        businessLineId: null,
        businessLineName: null,
        businessDepartmentId: null,
        businessDepartmentName: null,
        deliveryDepartmentId: null,
        deliveryDepartmentName: null,
        customerName: null,
        contractName: null,
        gp1TargetValue: null,
        regularSalary: null,
        fiveInsuranceAndOnePension: null,
        gp1RealityValue: null,
        deviationFromTargetValue: null,
        bonusFactor: null,
        havaLastCompanyBill: null,
        lastCompanyMonthlySalary: null,
        status: null,
        entryDate: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        contractId: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd () {
      this.reset();
      this.open = true;
      this.title = "添加客户信息";
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      this.isWatch = false
      this.reset();
      const id = row.id || this.ids
      getCustomer(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改客户信息";
        this.$nextTick(() => {
          this.isWatch = true
        })
      });
    },
    /** 提交按钮 */
    submitForm () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCustomer(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCustomer(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除客户信息编号为"' + ids + '"的数据项？').then(function () {
        return delCustomer(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport () {
      this.download('system/customer/export', {
        ...this.queryParams
      }, `customer_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
